package com.dhz.common.utils;

import javax.servlet.http.HttpServletRequest;

/**
 * IP工具类
 *
 * @author FY
 */
public class IpUtils {

    /** IP地址校验 */
    public static final String IP_PATTERN = "([1-9]|[1-9]\\d|1\\d{2}|2[0-4]\\d|25[0-5])(\\.(\\d|[1-9]\\d|1\\d{2}|2[0-4]\\d|25[0-5])){3}";
    public static final String IP_PATTERN_FIRST = "([1-9]|[1-9]\\d|1\\d{2}|2[0-4]\\d|25[0-5])";
    public static final String IP_PATTERN_FIELD = "(\\.(\\d|[1-9]\\d|1\\d{2}|2[0-4]\\d|25[0-5]))";

    private IpUtils() {
    }

    /**
     * 从Servlet的Request对象中获取请求发起者的IP
     * @param request {@link HttpServletRequest}
     * @return 返回IP地址字符串
     */
    public static String getIpFromServletRequest(HttpServletRequest request) {
        if (request == null) {
            return "unknown";
        }
        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("X-Forwarded-For");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("X-Real-IP");
        }

        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        return ip;
    }

    /**
     * IP格式校验
     * @param str 待校验字符串
     * @return 校验结果boolean值
     */
    public static boolean isIp(final String str) {
        return StrExtUtils.isNotEmpty(str) && str.matches(IP_PATTERN);
    }

}
